package com.example.springsecuritydemo01.service;

import com.example.springsecuritydemo01.pojo.entity.User;
import com.example.springsecuritydemo01.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SecurityService implements UserDetailsService {
    @Autowired
    private UserService userService;

    public SecurityService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVo user = userService.getUserInfo(username);
        List<String> roles = user.getRoles();
        List<String> powers = user.getPowers();
        if (user==null)
            throw new UsernameNotFoundException("user is not found");
        System.out.println(new BCryptPasswordEncoder().encode(user.getPassword()));
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();

        roles.forEach(role->authorityList.add(new SimpleGrantedAuthority("ROLE_"+role)));
        powers.forEach(power->authorityList.add(new SimpleGrantedAuthority(power)));

        return new org.springframework.security.core.userdetails.User(
                username,
                user.getPassword(),
                authorityList
            );
    }
}
